import Vue from "vue";
import Router from "vue-router";
import store from "../store/store";

import Layout from "../view/layout/layout.vue";
import DataManage from "../view/data/list.vue";
import HousingManage from "../view/house/list.vue";
import OperationsManage from "../view/operations/list.vue";
import BuildingManage from "../view/house/building/list.vue";
import BuildingForm from "../view/house/building/edit.vue";
import doorModelForm from "../view/house/doorModel/edit.vue";
import doorModelManage from "../view/house/doorModel/list.vue";
import RoomForm from "../view/house/room/edit.vue";
import RoomManage from "../view/house/room/list.vue";
import RepairManage from "../view/house/building/repairList.vue";
import RepairForm from "../view/house/building/repairEdit.vue";
import ContractManage from "../view/operations/Contract/list.vue";
import ContractForm from "../view/operations/Contract/edit.vue";
import TenantManage from "../view/operations/Tenant/list.vue";
import TenantForm from "../view/operations/Tenant/edit.vue";
import workOrderManage from "../view/operations/workOrder/list.vue";
import workOrderForm from "../view/operations/workOrder/edit.vue";
import messageManage from "../view/operations/message/list.vue";
import equipmentManage from "../view/operations/equipment/list.vue";
import equipmentForm from "../view/operations/equipment/edit.vue";
import login from "../view/layout/login.vue";
import redirect from "../view/layout/redirect.vue";
import visualization from "../view/visualization/index.vue";
import visualizationEdit from "../view/visualization/edit.vue";
import visualizationRoom from "../view/visualization/room.vue";
import costManage from "../view/cost/list.vue";
import costForm from "../view/cost/edit.vue";
import costNotice from "../view/cost/notice.vue";
import costMeterReading from "../view/cost/meterReading.vue";
import coefficientManage from "../view/cost/coefficient/list.vue";
import coefficientForm from "../view/cost/coefficient/edit.vue";
import coefficientDetail from "../view/cost/coefficient/detail.vue";
import coefficientRelation from "../view/cost/coefficient/relation.vue";
import taxRateManage from "../view/cost/taxRate/list.vue";
import taxRateRelation from "../view/cost/taxRate/relation.vue";
import NotFound from "../view/currency/404.vue";

import assessmentTarget from '../view/assessment/target'
import assessmentManage from '../view/assessment/manage'
import assessment from '../view/assessment/index'
import assessmentList from '../view/assessment/list'

import contract_management from '../view/v2/default?v=1'
import contract_template_management from '../view/v2/default?v=2'
import contract_review from '../view/v2/default?v=3'
import assetsmanagement from '../view/v2/default?v=4'
import assets_type from '../view/v2/default?v=5'
import supplier_management from '../view/v2/default?v=6'
import news_management from '../view/v2/default?v=7'
import carousel_management from '../view/v2/default?v=8'
import user_reserve_management from '../view/v2/default?v=9'
import mobile_settings from '../view/v2/default?v=10'
import announcement_management from '../view/v2/default?v=11'
import msg_management from '../view/v2/default?v=12'
import payment_settings from '../view/v2/default?v=13'
import customer_management from '../view/v2/default?v=14'
import property_maintenance_management from '../view/v2/default?v=15'
import maintenance_and_renovation_management from '../view/v2/default?v=16'
import room_empty_management from '../view/v2/default?v=17'
import energy_efficiency_management from '../view/v2/default?v=18'

Vue.use(Router);

//获取原型对象上的push函数
const originalPush = Router.prototype.push;

//修改原型对象中的push方法
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err);
};

//所有权限
let Power = {};

[
  "building",
  "repair",
  "doorModel",
  "room",
  "contract",
  "tenant",
  "work",
  "message",
  "equipment",
  "cost",
  "coefficient",
  "taxrate",
  'assessmentTarget',
  'assessmentManage',
  'assessmentIndex'
].forEach(v => (Power[v.toUpperCase()] = "/" + v));

[
  'contract_management',
  'contract_template_management',
  'contract_review',
  'assetsmanagement',
  'assets_type',
  'supplier_management',
  'news_management',
  'carousel_management',
  'user_reserve_management',
  'mobile_settings',
  'announcement_management',
  'msg_management',
  'payment_settings',
  'customer_management',
  'property_maintenance_management',
  'maintenance_and_renovation_management',
  'room_empty_management',
  'energy_efficiency_management'
].forEach(v => (Power[v.toUpperCase()] = "/default/" + v))


let aysncRoutes = [
  {
    path: "/",
    meta: {
      title: "数据中心",
      menu: false
    },
    component: DataManage
  },
  { path: 'assessmentTarget', meta: { title: '指标管理', auth: [Power.ASSESSMENTTARGET] }, component: assessmentTarget },
  { path: 'assessmentManage', meta: { title: '考核管理', auth: [Power.ASSESSMENTMANAGE] }, component: assessmentManage },
  { path: 'assessmentIndex', meta: { title: '我的考核', auth: [Power.ASSESSMENTINDEX] }, component: assessment },
  { path: 'assessmentList', meta: { title: '考核排行', auth: [Power.ASSESSMENTLIST] }, component: assessmentList },
  { path: 'default/contract_management', meta: { title: '合同管理', auth: [Power.CONTRACT_MANAGEMENT] }, component: contract_management },
  { path: 'default/contract_template_management', meta: { title: '合同模板', auth: [Power.CONTRACT_TEMPLATE_MANAGEMENT] }, component: contract_template_management },
  { path: 'default/contract_review', meta: { title: '合同审核', auth: [Power.CONTRACT_REVIEW] }, component: contract_review },
  { path: 'default/assetsmanagement', meta: { title: '资产台账管理', auth: [Power.ASSETSMANAGEMENT] }, component: assetsmanagement },
  { path: 'default/assets_type', meta: { title: '资产类别', auth: [Power.ASSETS_TYPE] }, component: assets_type },
  { path: 'default/supplier_management', meta: { title: '供应商管理', auth: [Power.SUPPLIER_MANAGEMENT] }, component: supplier_management },
  { path: 'default/news_management', meta: { title: '资讯管理', auth: [Power.NEWS_MANAGEMENT] }, component: news_management },
  { path: 'default/carousel_management', meta: { title: '轮播图管理', auth: [Power.CAROUSEL_MANAGEMENT] }, component: carousel_management },
  { path: 'default/user_reserve_management', meta: { title: '用户预约管理', auth: [Power.USER_RESERVE_MANAGEMENT] }, component: user_reserve_management },
  { path: 'default/mobile_settings', meta: { title: '移动端设置', auth: [Power.MOBILE_SETTINGS] }, component: mobile_settings },
  { path: 'default/announcement_management', meta: { title: '公告管理', auth: [Power.ANNOUNCEMENT_MANAGEMENT] }, component: announcement_management },
  { path: 'default/msg_management', meta: { title: '消息管理', auth: [Power.MSG_MANAGEMENT] }, component: msg_management },
  { path: 'default/payment_settings', meta: { title: '支付设置', auth: [Power.PAYMENT_SETTINGS] }, component: payment_settings },
  { path: 'default/customer_management', meta: { title: '客户管理', auth: [Power.CUSTOMER_MANAGEMENT] }, component: customer_management },
  { path: 'default/property_maintenance_management', meta: { title: '物业维修管理', auth: [Power.PROPERTY_MAINTENANCE_MANAGEMENT] }, component: property_maintenance_management },
  { path: 'default/maintenance_and_renovation_management', meta: { title: '维修改造管理', auth: [Power.MAINTENANCE_AND_RENOVATION_MANAGEMENT] }, component: maintenance_and_renovation_management },
  { path: 'default/room_empty_management', meta: { title: '房屋空置管理', auth: [Power.ROOM_EMPTY_MANAGEMENT] }, component: room_empty_management },
  { path: 'default/energy_efficiency_management', meta: { title: '能耗统计', auth: [Power.ENERGY_EFFICIENCY_MANAGEMENT] }, component: energy_efficiency_management },
  {
    path: "building",
    redirect: "/building/list",
    meta: {
      title: "楼宇管理",
      auth: [Power.BUILDING]
    },
    component: {
      render: h => h("router-view")
    },
    children: [
      {
        path: "list",
        component: BuildingManage
      },
      {
        path: "edit/:id?",
        component: BuildingForm
      }
    ]
  },
  {
    path: "doorModel",
    redirect: "/doorModel/list",
    meta: {
      title: "户型管理",
      auth: [Power.DOORMODEL]
    },
    component: {
      render: h => h("router-view")
    },
    children: [
      {
        path: "list",
        component: doorModelManage
      },
      {
        path: "edit/:id?",
        component: doorModelForm
      }
    ]
  },
  {
    path: "room",
    redirect: "/room/list",
    meta: {
      title: "房间管理",
      auth: [Power.ROOM]
    },
    component: {
      render: h => h("router-view")
    },
    children: [
      {
        path: "list",
        component: RoomManage
      },
      {
        path: "edit",
        component: RoomForm
      }
    ]
  },
  {
    path: "repair",
    redirect: "/repair/list",
    meta: {
      title: "维修记录",
      auth: [Power.REPAIR]
    },
    component: {
      render: h => h("router-view")
    },
    children: [
      {
        path: "list",
        component: RepairManage
      },
      {
        path: "edit/:id?",
        component: RepairForm
      }
    ]
  },
  {
    path: "contract",
    redirect: "/contract/list",
    meta: {
      title: "合同管理",
      auth: [Power.CONTRACT]
    },
    component: {
      render: h => h("router-view")
    },
    children: [
      {
        path: "list",
        component: ContractManage
      },
      {
        path: "edit/:id?",
        component: ContractForm
      }
    ]
  },
  {
    path: "tenant",
    redirect: "/tenant/list",
    meta: {
      title: "租户管理",
      auth: [Power.TENANT]
    },
    component: {
      render: h => h("router-view")
    },
    children: [
      {
        path: "list",
        component: TenantManage
      },
      {
        path: "edit/:type?/:id?",
        component: TenantForm
      }
    ]
  },
  {
    path: "cost",
    redirect: "/cost/list",
    meta: {
      title: "费用管理",
      auth: [Power.COST]
    },
    component: {
      render: h => h("router-view")
    },
    children: [
      {
        path: "list",
        component: costManage
      },
      {
        path: "edit/:id/:isExamine?",
        component: costForm
      },
      {
        path: "notice/:id?",
        component: costNotice
      },
      {
        path: "meterReading/:id?",
        component: costMeterReading
      }
    ]
  },
  {
    path: "coefficient",
    redirect: "/coefficient/list",
    meta: {
      title: "系数模板",
      auth: [Power.COEFFICIENT]
    },
    component: {
      render: h => h("router-view")
    },
    children: [
      {
        path: "list",
        component: coefficientManage
      },
      {
        path: "edit/:state/:id?",
        component: coefficientForm
      },
      {
        path: "detail/:id?",
        component: coefficientDetail
      },
      {
        path: "relation/:id?",
        component: coefficientRelation
      }
    ]
  },
  {
    path: "work",
    redirect: "/work/list",
    meta: {
      title: "工单管理",
      auth: [Power.WORK]
    },
    component: {
      render: h => h("router-view")
    },
    children: [
      {
        path: "list",
        component: workOrderManage
      },
      {
        path: "edit",
        component: workOrderForm
      }
    ]
  },
  {
    path: "message",
    redirect: "/message/list",
    meta: {
      title: "消息管理",
      auth: [Power.MESSAGE]
    },
    component: {
      render: h => h("router-view")
    },
    children: [
      {
        path: "list",
        component: messageManage
      }
    ]
  },
  {
    path: "equipment",
    redirect: "/equipment/list",
    meta: {
      title: "设备管理",
      auth: [Power.EQUIPMENT]
    },
    component: {
      render: h => h("router-view")
    },
    children: [
      {
        path: "list",
        component: equipmentManage
      },
      {
        path: "edit",
        component: equipmentForm
      }
    ]
  },
  {
    path: "taxrate",
    redirect: "/taxrate/list",
    meta: {
      title: "税率模板",
      auth: [Power.TAXRATE]
    },
    component: {
      render: h => h("router-view")
    },
    children: [
      {
        path: "list",
        component: taxRateManage
      },
      {
        path: "relation/:id?",
        component: taxRateRelation
      }
    ]
  },
  {
    path: "*",
    component: NotFound
  }
];

let constantRoutes = [
  {
    name: "login",
    path: "/login",
    component: login
  },
  {
    name: "redirect",
    path: "/redirect",
    component: redirect
  },
  // {
  //   path: "/visualization/index",
  //   component: visualization
  // },
  // {
  //   path: "/visualization/edit",
  //   component: visualizationEdit
  // },
  // {
  //   path: "/visualization/room",
  //   component: visualizationRoom
  // }
];

//获取权限
let filterPowerRoutes = function () {
  let powers = [];
  function getPowser(Menus) {
    Menus.forEach(v => {
      // 是否有子节点
      if (v.leafNode == "N" && v.childrenNode) {
        getPowser(v.childrenNode);
      } else if (v.leafNode == "Y") {
        powers.push(v.nodeUrl);
      }
    });
  }

  getPowser(store.state.user.MenuNode);
  let powserRoutes = [];
  aysncRoutes.forEach(v => {
    // 要是页面没有权限 或者 已有相应权限
    //console.info(JSON.stringify(v));
    if (!v.meta || !v.meta.auth || powers.some(p => p == v.meta.auth)) {
      powserRoutes.push(v);
    }
  });
  let obj = {
    path: "/",
    component: Layout,
    children: powserRoutes,
  };
  return obj;
};

let router = new Router({
  mode: 'history',
  routes: constantRoutes
});

/**
 *
 * 获取Menu的步骤
 * 先中台登录 获取Token
 * 获取中台用户详细信息, 获取App, 获取组织
 * 组织后获取管理处 App获取后 获取Menu
 * 传Token去Base后台
 * 登录进入
 * 有Token缓存进入
 */

//router跳转前
router.beforeEach(async (to, from, next) => {
  if (to.name != "login") {
    if (to.path === "/redirect") {
      next();
    } else {
      if (!store.getters.isLogin) {
        next({ path: "/login", query: { ReturnUrl: to.path } });
      } else {
        if (!store.state.isGenerate) {
          let rerouter = new Router({
            mode: 'history',
            routes: constantRoutes
          });
          router.matcher = rerouter.matcher;
          //是否内置
          if (store.getters.isAdmin) {
            // 跳过权限
            let obj = {
              path: "/",
              component: Layout,
              children: [...constantRoutes, ...aysncRoutes]
            };
            let tree = [
              { title: "房源管理", auths: [Power.BUILDING, Power.DOORMODEL, Power.ROOM, Power.REPAIR] },
              { title: "运维管理", auths: [Power.CONTRACT, Power.TENANT, Power.WORK, Power.MESSAGE, Power.EQUIPMENT] },
              { title: "费用管理", auths: [Power.COST, Power.COEFFICIENT, Power.TAXRATE] },
              {
                title: '考核管理', auths: [
                  Power.ASSESSMENTTARGET,
                  Power.ASSESSMENTMANAGE,
                  Power.ASSESSMENTINDEX,
                  Power.ASSESSMENTLIST,
                  Power.ASSESSMENTUSERS,
                  Power.ASSESSMENTPASSWORD]
              },
              { title: "能耗管理", auths: [Power.ENERGY_EFFICIENCY_MANAGEMENT] },
              { title: "租赁管理", auths: [Power.CONTRACT_MANAGEMENT, Power.CONTRACT_TEMPLATE_MANAGEMENT, Power.CONTRACT_REVIEW, Power.ROOM_EMPTY_MANAGEMENT] },
              { title: "资产管理", auths: [Power.ASSETSMANAGEMENT, Power.ASSETS_TYPE] },
              { title: "物业管理", auths: [Power.MAINTENANCE_AND_RENOVATION_MANAGEMENT, Power.PROPERTY_MAINTENANCE_MANAGEMENT, Power.SUPPLIER_MANAGEMENT] },
              { title: "移动门户管理", auths: [Power.CUSTOMER_MANAGEMENT, Power.NEWS_MANAGEMENT, Power.CAROUSEL_MANAGEMENT, Power.ANNOUNCEMENT_MANAGEMENT, Power.USER_RESERVE_MANAGEMENT, Power.MOBILE_SETTINGS] },
              { title: "业务设置", auths: [Power.MSG_MANAGEMENT, Power.PAYMENT_SETTINGS] }
            ];
            let admin = store.state.admin || {};
            admin.TwoTree = tree;
            admin.AdminMenu = aysncRoutes;
            store.commit('changeAdmin', admin);
            router.addRoutes([obj]);
          } else {
            router.addRoutes([filterPowerRoutes()]);
          }

          store.commit("changeGenerate", true);

          // 第一次进入时 路由routes可能未生成完成，这个时候的next并未匹配到相应的路由记录。
          // 在addRoutes后重新在跳转一次即可解决，replace--不留下浏览器历史记录。
          next({ ...to, replace: true });
        } else next();
      }
    }


  } else next();
});

export default router;
